package com.delianna.bwt;

import java.util.Date;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;

import com.delianna.bwt.data.XmlParser;
import com.delianna.bwt.helpers.AppStatus;
import com.delianna.bwt.models.BWT;

public class RefreshDataActivity extends Activity {
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.loading);
		
		// execute your xml loader
		new AsyncLoadXMLFeed().execute();
	}

	private class AsyncLoadXMLFeed extends AsyncTask<Void, Void, Void> {

		private BWT bwt;

		@Override
		protected void onPreExecute() {
			// show your progress dialog
		}

		@Override
		protected Void doInBackground(Void... params) {
			// load your xml feed asynchronously
			boolean isOnline = AppStatus.getInstance(RefreshDataActivity.this).isOnline(RefreshDataActivity.this);
			bwt = XmlParser.Parse(true, isOnline);
			return null;
		}

		@Override
		protected void onPostExecute(Void params) {
			// dismiss your dialog
			// launch your activity
			Intent intent = new Intent(RefreshDataActivity.this,
					PortListActivity.class);
			
			if (bwt != null) setResult(1,intent);
			intent.putExtra("com.delianna.bwt.models.BWT", bwt);
			setLastUpdateTime();

			// close this activity
			finish();
		}
		
		private void setLastUpdateTime(){
			SharedPreferences prefs = PreferenceManager
					.getDefaultSharedPreferences(RefreshDataActivity.this);
			SharedPreferences.Editor editor = prefs.edit();
			long date = new Date().getTime();
			editor.putLong("lastUpdate", date);
			editor.commit();
		}
	}
}
